﻿using AutoMapper;
using Easy.Common.Extension;
using Easy.Common.Helper;
using Easy.Common.Params;
using Easy.Common.Results;
using Easy.Services.Dtos;
using Easy.Services.Entities;
using Easy.Services.Interface;
using Microsoft.AspNetCore.Mvc;

namespace Easy.API.Controllers
{
    /// <summary>
    /// UserInfo
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class UserController(IMapper _mapper,
        IUserService _userService,
        IUserRoleRelationService _roleRelationService,
        ICompanyService _companyService) : BaseController
    {
        readonly IMapper mapper = _mapper;

        readonly IUserService userService = _userService;

        readonly IUserRoleRelationService roleRelationService = _roleRelationService;

        readonly ICompanyService companyService = _companyService;


        #region sync base

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="login">实体</param>
        /// <returns>返回结果</returns>
        [HttpPost(nameof(Login))]
        public APIResult Login(LoginDTO login)
        {
            APIResult result = new();
            if (!ModelState.IsValid)
            {
                result.Message = "验证未通过";
                return result;
            }
            result = userService.Login(login);

            return result;
        }

        [HttpPost(nameof(Register))]
        public APIResult Register(LoginDTO dto)
        {
            APIResult result = new();
            if (!ModelState.IsValid)
            {
                result.Message = "验证未通过";
                return result;
            }
            var ip = HttpContext.GetClientIP();
            result = userService.Register(dto, ip);
            return result;

        }


        [HttpGet(nameof(Profile))]
        public APIResult Profile() => userService.GetProfile(tokenModel: TokenModel);


        [HttpPost(nameof(AssignRoles))]
        public APIResult AssignRoles(UserRoleRelationDTO dto)
        {
            APIResult result = new();
            List<UserRoleRelation> relations = [];
            foreach (var item in dto.RoleIds)
            {
                if (relations.Any(r => r.RoleId == item))
                    continue;
                var model = new UserRoleRelation() { UserId = dto.UserId, RoleId = item };
                model.SetModelBase(tokenModel: TokenModel, true);
                relations.Add(model);
            }
            if (relations.Count <= 0)
            {
                result.Message = "参数为空";
                return result;
            }
            var list = roleRelationService.GetList(r => r.UserId == dto.UserId);
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    item.SetModelBase(tokenModel: TokenModel);
                    item.SetDelete();
                }
                roleRelationService.UpdateBatch(list);
            }
            result.Success = roleRelationService.AddBatch(relations);
            result.Message = result.Success ? "添加成功" : "添加失败";
            return result;

        }

        /// <summary>
        /// 更新密码
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost(nameof(UpdatePassword))]
        public APIResult UpdatePassword(UpdatePasswordDTO dto)
        {
            APIResult result = new();
            if (!ModelState.IsValid)
            {
                result.Message = "请求参数不完整!";
                return result;
            }
            if (dto.NewPassword.Equals(dto.OldPassword))
            {
                result.Message = "新旧密码一致!";
                return result;
            }
            result = userService.UpdatePassword(dto, TokenModel);
            return result;
        }

        [HttpGet(nameof(ResetToken))]
        public APIResult ResetToken()
        {
            APIResult result = new()
            {
                Success = true,
                Message = "重置成功"
            };
            return result;
        }


        [HttpGet(nameof(GetManagerList))]
        public APIResult GetManagerList() => userService.GetManagerList();


        [HttpPost(nameof(AddUser))]
        public APIResult AddUser(AddUserDTO dto)
        {
            var model = mapper.Map<User>(dto);
            var company = companyService.Get(c => c.Id == model.DepartmentId);
            model.DepartmentName = company?.Name ?? "";
            model.PasswordSalt = CommonHelper.CreateVerifyCode(6);
            model.Password = CommonHelper.CalcMD5("123456" + model.PasswordSalt);
            model.SetModelBase(tokenModel: TokenModel, isInit: true);
            var result = userService.AddUser(model);
            var user = userService.Get(u => u.UserName == model.UserName);
            user.WorkNumber = user.Id.ToString("D6");
            userService.Update(user);
            return result;

        }


        [HttpPost(nameof(GetPage))]
        public APIResult GetPage(UserPageParam param) => userService.GetPage(param);


        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="resetPassword"></param>
        /// <returns></returns>
        [HttpPut(nameof(ResetPassword))]
        public APIResult ResetPassword(long id)
        {
            APIResult result = new();
            var user = userService.Get(u => u.Id == id);
            if (user != null)
            {
                user.PasswordSalt = CommonHelper.CreateVerifyCode(6);
                user.Password = CommonHelper.CalcMD5("123456" + user.PasswordSalt);
                result.Success = userService.Update(user);
            }
            result.Message = "重置失败";
            return result;

        }


        [HttpDelete(nameof(Delete))]
        public APIResult Delete(long id)
        {
            APIResult result = new();
            if (id == 1)
            {
                result.Message = "系统保留不允许删除";
                return result;
            }
            var model = userService.Get(p => p.Id == id);
            if (model == null)
            {
                result.Message = "数据不存在";
                return result;
            }
            model.SetModelBase(tokenModel: TokenModel);
            model.SetDelete();
            var res = userService.Delete(model);
            result.Success = res;
            result.Message = res == true ? "删除成功" : "删除失败";
            return result;

        }

        
        [HttpGet("{id}")]
        public APIResult Get(long id)
        {
            APIResult result = new();
            var user = userService.Get(u => u.Id == id);
            if (user == null)
            {
                result.Message = "获取失败";
                return result;
            }
            var dto = mapper.Map<UserDTO>(user);
            result.Success = true;
            result.Data = dto;
            return result;


        }


        [HttpPost(nameof(Update))]
        public APIResult Update(UpdateUserDTO dto)
        {
            APIResult result = new();
            var model = mapper.Map<User>(dto);
            model.SetModelBase(tokenModel: TokenModel);
            var user = userService.Get(u => u.Id == dto.Id);
            if (user == null)
            {

                result.Message = "员工不存在";
                return result;
            }
            model.City = user.City;
            model.CreaterDate = user.CreaterDate;
            model.CreaterId = user.CreaterId;
            model.CreaterName = user.CreaterName;
            model.Password = user.Password;
            model.PasswordSalt = user.PasswordSalt;
            model.LastLoginDate = user.LastLoginDate;
            result.Success = userService.Update(model);
            return result;

        }

        [HttpGet(nameof(GetRoleIds)+ "/{id}")]
        public APIResult GetRoleIds(long id)
        {
            APIResult result = new();
            if (id <= 0)
            {
                result.Message = "登录信息异常，重新登录获取";
                return result;
            }
            var roleIds = userService.GetRoleIds(id);
            result.Success = true;
            result.Data = roleIds;
            return result;
        }

        #endregion


    }
}
